<template>
<!--登录-->
    <div class="login">
      <div class="content">
        <div class="container clearfix">
          <div  class="prism-player" id="J_prismPlayer"></div>
          <img src="../../assets/login.png" alt="" width="372">
          <div class="login_form">
            <p>绑定手机号</p>
            <Form ref="phone" :model="val" :rules="phoneRule">
              <FormItem prop="phone">
                <Input v-model="val.phone" placeholder="手机号" ref="phoneA1"  @on-keyup="validatePhoneA1" :maxlength="11" />
              </FormItem>
              <FormItem prop="code">
                <Input v-model="val.smscode" placeholder="验证码"  ref="codeA1" :maxlength="6" @on-keyup="validateCodeA1" @keydown.enter.native="bind"/>
                <Button type="primary" size="large" class="send" :class="{disabled:codeUse}" @click.stop="getSmscode('phone')" >{{tip}}</Button>
              </FormItem>
              <FormItem>
                <Button type="primary" long class="loginbtn" @click.stop="bind">绑定手机号</Button>
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
      <Spin fix v-show="isSpinShow" >
        <div class="loader">
          <Icon type="ios-loading" size=26 class="demo-spin-icon-load"></Icon>
          <div class="font14">加载中...</div>
        </div>
      </Spin>
    </div>
</template>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less" rel="stylesheet/less">
  /* 旋转效果 */
  .demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50% { transform: rotate(180deg);}
    to { transform: rotate(360deg);}
  }
  /* 假如内容过长，一屏放不下，滚动条下拉覆盖不全 */
  .ivu-spin-fix {
    position: fixed;
  }

  .login{
    background: url("../../assets/loginbg.png") no-repeat ;
    width: 100%;
    min-height: 1080px;
    height: 100%;
    background-size: 100% 100%;
    .content{
      width: 1000px;
      height: 600px;
      background-color: #fff;
      border-radius: 5px;
      position: absolute;
      top:50%;
      left: 50%;
      margin-top: -300px;
      margin-left: -500px;
      padding: 150px 100px;
      .container{
        >img,.login_form{
          float: left;
        }
        .login_form{
          width: 340px;
          margin-left: 88px;
          a{
            display: block;
          }
          p{
            font-size: 20px;
            color: #000;
            text-align: left;
            margin-bottom: 20px;
          }
            input{
              border-radius: 0;
              display: inline-block;
              width: 80%;
            }
          button{
            background-color: #957960;
            border-color: #957960;
          }
            .send{
              position:absolute ;
              right: 0;
              top: 0;
              height: 40px;
              border-top-left-radius: 0;
              border-bottom-left-radius: 0;
            }
          .loginbtn{
            height: 50px;
            font-size: 18px;
          }
          }
        .other{
          span{
            margin-right: 40px;
            /*font-size: 16px;*/
            color: #999;
          }
          a{
            display: inline-block;
          }
          .margin20{
            margin: 0 40px;
          }
          img{
            vertical-align: middle;
          }
        }


      }
    }
  }
</style>
<script type="text/ecmascript-6">
  import {getMobile, sendSms, loginApp, bindMobile, initLogin} from '../../http'
  import {setStore,getStore} from '../../storage'
    export default {
        name: 'login',
        props: {},
        data() {
            return {
              isSpinShow:false,
              //后台返回绑定数据
              accountId:this.$route.query.accountId,
              userName:this.$route.query.username,
              type:this.$route.query.type,
              //获取验证码
              val:{
                phone:'',
                smscode:''
              },
              codeUse:false,
              tip:'发送验证码',
              count: 0,
              mobile:'',
              time:'1',
              //手机号码表单认证
              phoneRule:{
                phone:[
                  {required:true, message:'请填写手机号', trigger:'blur' },
                  {type: 'string',pattern :/^[1][3,4,5,7,8][0-9]{9}$/ ,message:'请正确填写手机号',trigger:'blur'}
                ]
              },
            };
        },
        methods: {
          //数字输入框
          validatePhoneA1() {
            this.val.phone = this.$refs.phoneA1.value.replace(/[^\d]{1,11}/g, "")
          },
          validateCodeA1() {
            this.val.smscode = this.$refs.codeA1.value.replace(/[^\d]{1,11}/g, "")
          },
          //绑定手机号
          bind(){
            if(this.val.smscode.length === 0){
              this.$Notice.warning({
                title: "验证码提醒",
                desc: "请填写验证码",
                duration: 3,
              });
            }else{
              if(this.isSpinShow === false) {
                this.isSpinShow = true;
                //第三方绑定手机号
                bindMobile({accountId: this.accountId, mobile: this.val.phone, smsCode: this.val.smscode}).then(res => {
                  if (res.code === 200) {
                    this.$Notice.success({
                      title: '绑定手机号提醒',
                      desc: '绑定手机号成功！',
                      duration: 3,
                    });
                    // this.autoLogin(this.userName)
                    loginApp({username:this.userName,password:'123456'}).then(res => {
                      this.isSpinShow = false;
                      if(res.code === 200) {
                        setStore('token', res.data.access_token);
                        setStore('refresh_token', res.data.refresh_token);
                        if(this.type === 'n'){
                          this.$router.push({
                            name: 'index',
                          });
                        }else {
                          initLogin().then(res => {
                            //初始化方法无论成功与否都跳转主页（如果用户是第二次进入初始化失败也做跳转）
                            this.$router.push({
                              name: 'index',
                            });
                           /* if (res.code === 200) {
                              this.$router.push({
                                name: 'index',
                              });
                            } else {
                              this.$Notice.warning({
                                title: '绑定手机号提醒',
                                desc: res.info,
                                duration: 3,
                              });
                            }*/
                          }).catch()
                        }
                      }else{
                        this.$Notice.warning({
                          title: '账号登录提醒',
                          desc: res.info,
                          duration: 3,
                        });
                      }
                    }).catch()
                  } else {
                    this.isSpinShow = false;
                    this.$Notice.warning({
                      title: '绑定手机号提醒',
                      desc: res.info,
                      duration: 3,
                    });
                  }
                }).catch()
              }
            }
          },
          //获取验证码
          getSmscode(name){
            this.$refs[name].validate((valid) => {
              if(valid){
                getMobile({mobile:this.val.phone}).then(res => {
                  if(res.code === 200){
                    this.mobile = res.data.mobile;
                    this.time = res.data.time;
                    const TIME_COUNT = 60;
                    if (!this.timer) {
                      //获取验证码
                      sendSms({mobile:this.mobile,time:this.time}).then(res => {
                        if(res.code === 200){
                          this.count = TIME_COUNT;
                          //自动填充验证码
                          // this.val.smscode = res.data;
                          //验证码倒计时
                          this.timer = setInterval(() => {
                            if (this.count > 0 && this.count <= TIME_COUNT) {
                              this.codeUse = true;
                              this.tip = this.count+"s后重新发送";
                              this.count--;
                            } else {
                              clearInterval(this.timer);
                              this.tip = '发送验证码';
                              this.codeUse = false;
                              this.timer = null;
                            }
                          }, 1000)
                        }else{
                          this.$Notice.warning({
                            title: '绑定手机号提醒',
                            desc: res.info,
                            duration: 3,
                          });
                        }
                      }).catch();
                    }
                  }
                }).catch()
              }else {
                this.$Notice.warning({
                  title: '绑定手机号提醒',
                  desc: "请正确填写手机号！",
                  duration: 3,
                });
              }
            }).catch()
          },
          //第三方绑定手机后登陆
          autoLogin(userName){
            loginApp({username:userName,password:'123456'}).then(res => {
              this.isSpinShow = false;
              if(res.code === 200) {
                setStore('token', res.data.access_token);
                setStore('refresh_token', res.data.refresh_token);
                if(this.type === 'n'){
                  this.$router.push({
                    name: 'index',
                  });
                }else {
                  initLogin().then(res => {
                    if (res.code === 200) {
                      this.$router.push({
                        name: 'index',
                      });
                    } else {
                      /*this.$Notice.warning({
                        title: '绑定手机号提醒',
                        desc: res.info,
                        duration: 3,
                      });*/
                    }
                  }).catch()
                }
              }else{
                this.$Notice.warning({
                  title: '账号登录提醒',
                  desc: res.info,
                  duration: 3,
                });
              }
            }).catch()
          }
        },
        created() {
          if(this.isSpinShow === false) {
            this.isSpinShow = true;
            //type从后台传来，n:用户已经绑定手机号，获取token跳转首页，b：用户未绑定手机号，绑定手机号
            if (this.type === 'n') {
              this.autoLogin(this.userName)
            }else {
              this.isSpinShow = false;
            }
          }
        },
        components: {}
    }
</script>
